<template>
	<view >
		<!-- 新增颜色图例 -->
		<view class="map-legend">
			<view class="legend-item" v-for="(item, index) in legendColors" :key="index" 
				@click="toggleColorFilter(item.color)"
				:style="{ borderColor: 'transparent' }">
				<view class="stats-value-count" :style="{ backgroundColor: item.color }">{{ colorStats[item.color] || 0 }}</view>
				<text class="legend-text">{{ item.label }}</text>
				<!-- <text class="stats-value-count" :style="{'background-color':item.color}">{{ colorStats[item.color] || 0 }}</text> -->
			</view>
		</view>
				
	<view class="box-infos   font12" >
		
		<view class="content-box ">
			<view class="boxsss100" style="display: flex;">
			
				<view class="top-but-box" style="float: none;">
					<view class="input_confirms maxwidth250 floatleft">
						<uni-data-select
						:localdata="$routeData.getRoute()"
						v-model="headerSearch.route_id"
						@change="(e)=>{$routeData.SetNowRoute(e),formsubmit(e)}"
						placeholder="选择仓库线路"
						placeholder-class="placeholder-class"
						class="color-e40318"
						></uni-data-select>
					</view>
					<view class="input_confirms maxwidth250 floatleft" >
						<uni-data-select
						:localdata="$routeData.getGroup()"
						v-model="headerSearch.group_id"
						@change="(e)=>{$global.setStorageRoute('group',e),formsubmitGroup(e)}"
						placeholder="选择用户分组"
						placeholder-class="placeholder-class"
						class="color-e40318"
						></uni-data-select>
					</view>
					<view class="input_confirms maxwidth250 floatleft" >
						<uni-data-select
						:localdata="$routeData.getLevel()"
						v-model="headerSearch.level_id"
						@change="(e)=>{$global.setStorageRoute('level_id',e),formsubmitLevel(e)}"
						placeholder="选择价格等级"
						placeholder-class="placeholder-class"
						class="color-e40318"
						></uni-data-select>
					</view>
					<!-- 搜索 -->
					<view class="w333 flex floatleft">
						<view class="riskTitle">客户名称:</view>
						<view class="searchBox " >
							<input
							v-model="headerSearch.word" 
							placeholder="输入客户档口 人名 手机 拼音进行搜索"
							placeholder-class="placeholder-class"
							@confirm="$common.noMultipleClicks('loadData',loadData,true)"
							class="search-ipu w200"
							/>
							<view class="delete-ipu" v-if="headerSearch.word!=''" @click="headerSearch.word=''">
								<img src="../../static/img/delete-1.png"></img>
							</view>
						</view>
					</view>

					<view @click="$common.noMultipleClicks('loadData',loadData,true)" class="add_color search-but">
						<img src="../../static/img/search.png" class="img" ></img>
						刷新数据
					</view>
					
					<view 
						:style="{'background-color':isLoadPoi==false?'#ff4444':'#666666'}"
						@click="openPoi" 
						class="back_color search-but " 
					>
						{{isLoadPoi==false?'打开客资线索':'关闭客资线索'}}
					</view>
					
					<view 
						style="background-color: #0f66e0;"
						@click="$refs.upload_amap.open()" 
						class="back_color search-but " 
					>
						<img src="../../static/img/update.png" class="ico"></img>
						更新索引库
					</view>
				</view>
				
				
					<map
					style="width: 100%;height: calc(100% - 54px);margin: 10px 0px;"
					:longitude="$routeData.getLatlng().longitude"
					:latitude="$routeData.getLatlng().latitude"
					:markers="markers"
					:include-points="include_points.length ? include_points:[{longitude:$routeData.getLatlng().longitude,latitude:$routeData.getLatlng().latitude}]"
					@callouttap="callouttap"
					>
					</map>
			</view>
			
		</view>
	</view>

		
		<!-- 线索库 -->
		<uni-popup ref="upload_amap" type="center" title="客源线索库" width="70%" height="90%">
			<upload_amap
			class="h100"
			></upload_amap>
		</uni-popup>
		
		
		<poi_confirm ref="poi_confirm"></poi_confirm>
		
		<!-- 打开用户页面 -->
		<uni-popup ref="page_money" type="center" :title="pageSearch.value + pageSearch.name">
			<person_admin
			:OnPageSearchUserId="pageSearch.value"  status="firm_user_list" class="h100"
			></person_admin>
		</uni-popup>
	</view>
</template>

<script>
	import person_admin from "@/components/user/list.vue"
	import upload_amap from "@/pages/map/upload_amap.vue"
	import poi_confirm from "@/pages/map/poi_confirm.vue"
	export default {
		components: {
			person_admin,upload_amap,poi_confirm
		},
		data() {
			return {
				markers:[],
				include_points:[],
				
				headerSearch:{//左边的树形框 搜索
					route_id:'',//获取某个目录下的商品
					group_id:'0',
					level_id:'0',
					word:''
				},
				pageSearch:{
					value:'',
					name:''
				},
				isLoadPoi:false,
				PoiList:[],
				// 新增数据项
				legendColors: [
					{ color: '#ff4444', label: '0-1天', days: [0,1],count:0 },
					{ color: '#ffa500', label: '2-3天', days: [2,3],count:0 },
					{ color: '#00cc66', label: '4-7天', days: [4,7],count:0 },
					{ color: '#666666', label: '30天外未下单', days: [30],count:0 },
					{ color: '#0f66e0', label: '客源线索', days: [-1000],count:0 },
				],
			}
		},
		onLoad() {
			let route = this.$routeData.GetNowRoute()
			this.headerSearch.route_id = route
			this.loadData()
		},
		created() {
			let route = this.$routeData.GetNowRoute()
			this.headerSearch.route_id = route
			this.loadData()
		},
		computed:{
			totalUsers(){
				return this.markers.length
			},
			colorStats(){
				const stats = {}
				this.markers.forEach(marker => {
					const color = marker.callout.bgColor
					stats[color] = (stats[color] || 0) + 1
				})
				return stats
			}
			
		},
		methods: {
			openPoi(){
				if(this.isLoadPoi== false){
					this.loadDataPio()
					this.isLoadPoi = true
				}
				else{
					this.loadData(true)
				}
			},
			// 修改后的颜色生成方法
			getMarkerColor(days) {
				if (days >= 30) return '666666'
				if (days <= 1 && days >=0) return 'ff4444'
				if (days <= 3 && days >=0) return 'ffa500'
				if (days == -1000) return '0f66e0'
				return '00cc66'
			},
			//打开客户卡
			callouttap(res){
			
				//检查是否为线索
				var data = this.getPoiData(res.detail.markerId)
				if(data!=false){
					this.$refs.poi_confirm.openPopup(data)
					return
				}
				this.pageSearch.value = res.detail.markerId+''
				this.$refs.page_money.open()
			},
			getPoiData(markerId){
				let list = this.PoiList
				for(var i=0;i<list.length;i++){
					if(markerId == list[i].uid){
						return list[i];
					}
				}
				return false
			},
			//选择价格等级
			formsubmitLevel(e){
				this.headerSearch.word  = ''
				this.headerSearch.group_id = e
				this.loadData()
			},
			/**
			 * 选择用户分组
			*/
			formsubmitGroup(e){
				this.headerSearch.word  = ''
				this.headerSearch.group_id = e
				this.loadData()
			},

			/**
			 * 选择仓库线路
			*/
			formsubmit(e){
		
				this.headerSearch.word  = ''
				this.headerSearch.route_id = e
				this.loadData()
			},

			// 修改后的loadData方法
			loadData(isUpdatePage = true) {
				var that = this
				that.$common.get_request(
					{
						type:'firm_user_list',
						search:that.headerSearch.word,//搜索内容
						route_id: that.headerSearch.route_id,//获取某个目录下的商品
						group_id: that.headerSearch.group_id,//获取某个目录下的商品
						level_id: that.headerSearch.level_id,//获取某个目录下的商品
						is_map:1
					},
					(res)=>{
						if (res.list.length === 0) {
							this.$common.toast("查找失败，可以试试更换关键字")
							return
						}
						this.isLoadPoi = false
						// 生成标记点（修改颜色生成方式）
						this.markers = res.list
							.filter(item => item.latlng)
							.map(item => {
								const json = JSON.parse(item.latlng)
								return this.createMarkersUser(
									{ latitude: json.lat, longitude: json.lng },
									item.id,
									'/static/map/'+this.getMarkerColor(item.orderEnd.days)+'.png',
									item.name,
									item.route_id,
									this.getMarkerColor(item.orderEnd.days),
									false,
									'#fff'
								)
							})
						this.include_points = this.markers
					},
					()=>{
					}
				)
			},
			// 修改后的loadData方法
			loadDataPio() {
				var that = this
				that.$common.get_request(
					{
						type:'get_upload_map'
					},
					(res)=>{
						if (res.list.length === 0) {
							return
						}
						this.PoiList = res.list
						var newMarkers = [];
						res.list.forEach((item, index) => {
						  const latitude = parseFloat(item.latitude);
						  const longitude = parseFloat(item.longitude);
						  
						  if (!isNaN(latitude) && !isNaN(longitude)) {
							 newMarkers.push(
						      this.createMarkersUser(
						        { latitude:latitude, longitude:longitude }, // 修正经纬度
						        item.uid,
						        `/static/map/${this.getMarkerColor(-1000)}.png`,
						        item.name,
						        -1,
						        this.getMarkerColor(-1000),
								true,
								'#fff'
						      )
						    );
						  } else {
						    console.error('无效的经纬度数据：', item);
						  }
						});
						
						// 4. 批量更新标记
						this.markers = [...this.markers, ...newMarkers];
						this.include_points = [...this.include_points, ...newMarkers];
						console.log(this.include_points)
				})
			},
			/**
			 * 创建用户标记点 
			 * */
			createMarkersUser(location, user_id, avatar, callout_content, route_id, bgColor,isPoi,color='#fff') {
				console.log("map",location)
				return {
					id: parseFloat(user_id),
					...location,
					iconPath: avatar,
					width: 10,
					height: 10,
					anchor: { x: 0.5, y: 1 }, // 关键修复：x轴居中，y轴底部对齐
					callout: {
						textAlign: 'center',
						bgColor: '#'+bgColor,
						color: color,
						content: callout_content,
						display: 'ALWAYS',
						borderRadius: 10,
						padding: 5,
						fontSize: 12
					},
					isPoi:isPoi,
					animation: 'fadeIn 0.5s'
				}
			},
		},
	}
</script>

<style>
	.pagesHeaderhBox{
		width: 100%;
		overflow: hidden;
	}
		/* 新增样式 */
		.stats-panel {
			position: absolute;
			top: 0px;
			right: 20px;
			background: rgba(255,255,255,0.95);
			padding: 15px;
			border-radius: 8px;
			z-index: 999;
			box-shadow: 0 2px 12px rgba(0,0,0,0.1);
		}

	
	

	
	.stats-item {
		display: flex;
		align-items: center;
		margin: 5px 0;
	}
	.stats-title {
		font-weight: bold;
		color: #e40318;
		margin-bottom: 10px;
		text-align: center;
	}

	.stats-item {
		display: flex;
		align-items: center;
		margin: 8px 0;
	}



	.stats-label {
		color: #666;
		margin-right: 8px;
		min-width: 80px;
	}

	.stats-value {
		color: #333;
		font-weight: bold;
	}
	.color-dot {
		width: 12px;
		height: 12px;
		border-radius: 50%;
		margin-right: 8px;
	}
	
	.map-legend {
		position: absolute;
		bottom: 20px;
		right: 20px;
		background: rgba(255,255,255,0.95);
		padding: 10px;
		border-radius: 8px;
		z-index: 999;
	}
	
	.legend-item {
		display: flex;
		align-items: center;
		padding: 6px 10px;
		margin: 4px 0;
		border: 2px solid transparent;
		border-radius: 6px;
		cursor: pointer;
	}
	.legend-item:hover{
		border: 2px solid #e40318;
	}


	.legend-text {
		font-size: 12px;
		color: #333;
		margin-left: auto;
	}
	.stats-value-count{
		padding: 3px;
		font-size: 12px;
		color: #fff;
		margin-left: -10px;
		min-width: 50px;
		border-radius: 4px;
		text-align: center;
	}

</style>
